package com.jinzo.mporaba.tasks;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
//import android.util.Log;

import com.jinzo.mporaba.DBAdapter;
import com.jinzo.mporaba.Mporaba;
import com.jinzo.mporaba.QuotaItem;

public class LoadFromCPTask implements Runnable {
	private Context context;
	private Handler callback;
	private ArrayList<QuotaItem> al_results = new ArrayList<QuotaItem>();

	public LoadFromCPTask() {
	}
	
	public void load(Context context, Handler callback) {
		this.context = context;
		this.callback = callback;
		
		Thread thread = new Thread(this);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void run() {
		ContentResolver cr = context.getContentResolver();
		Cursor c = cr.query(QuotaItem.CONTENT_URI, null, null, null, null);
		if (c != null && (c.getCount() > 0)) {
			c.moveToFirst();
			do {
				boolean prepaid = false;
				if (c.getInt(c.getColumnIndex(DBAdapter.KEY_PREPAID)) == 1) {
					prepaid = true;
				} else {
					prepaid = false;
				}
				this.al_results.add(new QuotaItem(c.getString(c.getColumnIndex(DBAdapter.KEY_DISPLAYNAME)), prepaid, c.getString(c.getColumnIndex(DBAdapter.KEY_UNIT)), c.getString(c.getColumnIndex(DBAdapter.KEY_AVAILABLE)), c.getString(c.getColumnIndex(DBAdapter.KEY_USED))));
				//Log.i("LoadFromCPTask", "Loaded QuotaItem");
			} while (!c.isLast() && c.moveToNext()); /* FIXIT: Hacky */
			c.close();
		}
		callback.sendEmptyMessage(Mporaba.REQUEST_SUCCESS);
	}
	
	public ArrayList<QuotaItem> getResult() {
		return this.al_results;
	}
}
